package com.memory.admin.user.controller;

import com.memory.common.utils.ResultVoUtil;
import com.memory.common.vo.ResultVo;
import com.memory.component.actionLog.action.UserAction;
import com.memory.component.actionLog.annotation.EntityParam;
import com.memory.modules.business.domain.user.Account;
import com.memory.modules.business.service.user.AccountService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * @PackageName: com.memory.admin.user.controller
 * @ClassName: UserController
 * @Description:
 * @author: zhuguangxun
 * @date 2021/3/10
 */
@Controller
@RequestMapping("/business/user")
@RequiredArgsConstructor
public class AccountController {

    private final AccountService accountService;

    @GetMapping("/list")
    public String list(Model model, Account account) {
        ExampleMatcher matcher = ExampleMatcher.matching();
        Example<Account> example = Example.of(account, matcher);
        final Page<Account> page = accountService.findPage(example);
        model.addAttribute("list", page.getContent());
        model.addAttribute("page", page);
        return "/business/user/list";
    }


    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    public String toAdd() {
        return "/business/user/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    public String toEdit(@PathVariable("id") Long id, Model model) {
        final Optional<Account> byId = accountService.findById(id);
        model.addAttribute("account", byId.orElse(new Account()));
        return "/business/user/add";
    }

    @GetMapping("/remove/{id}")
    @ResponseBody
    public ResultVo removeUser(@PathVariable("id") Long id,Model model){
        final Account remove = accountService.remove(id);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 保存添加/修改的数据
     */
    @PostMapping("/save")
    @ResponseBody
    @com.memory.component.actionLog.annotation.ActionLog(key = UserAction.USER_SAVE, action = UserAction.class)
    public ResultVo save(@EntityParam Account sell) {
        if (sell.getId() != null) {
            accountService.modify(sell.getId(), sell);
        } else {
            accountService.create(sell);
        }
        return ResultVoUtil.SAVE_SUCCESS;
    }
}
